package bot

import (
	"encoding/json"
	"go-api-template/internal/util/httpUtil"
	"go-api-template/service"
)

type BotMessage struct {
	MsgType string `json:"msg_type"`
	Content struct {
		Post struct {
			ZhCn struct {
				Title   string `json:"title"`
				Content [][]BotContent
			} `json:"zh_cn"`
		} `json:"post"`
	} `json:"content"`
}

type BotInteractive struct {
	ChatID  string `json:"chat_id"`
	MsgType string `json:"msg_type"`
	RootID  string `json:"root_id"`
	Card    struct {
		Header struct {
			Title struct {
				Tag     string `json:"tag"`
				Content string `json:"content"`
			} `json:"title"`
		} `json:"header"`
		Elements []Element `json:"elements"`
	} `json:"card"`
}

type BotContent struct {
	Tag    string `json:"tag"`
	Text   string `json:"text"`
	Href   string `json:"href"`
	UserId string `json:"user_id"`
}

type BotCard struct {
	MsgType string `json:"msg_type"`
	Card    struct {
		Config struct {
			WideScreenMode bool `json:"wide_screen_mode"`
			EnableForward  bool `json:"enable_forward"`
		} `json:"config"`
		Elements []Element `json:"elements"`
		Header   struct {
			Title struct {
				Content string `json:"content"`
				Tag     string `json:"tag"`
			} `json:"title"`
		} `json:"header"`
	} `json:"card"`
}

type Element struct {
	Tag     string   `json:"tag"`
	Text    Text     `json:"text,omitempty"`
	Actions []Action `json:"actions,omitempty"`
}

type Text struct {
	Content string `json:"content"`
	Tag     string `json:"tag"`
}

type Action struct {
	Tag  string `json:"tag"`
	Text struct {
		Content string `json:"content"`
		Tag     string `json:"tag"`
	} `json:"text"`
	URL   string `json:"url"`
	Type  string `json:"type"`
	Value struct {
	} `json:"value"`
}

func (b *BotMessage) AppendText(s string) {
	b.Content.Post.ZhCn.Content = append(b.Content.Post.ZhCn.Content, []BotContent{{
		Tag:  "text",
		Text: s,
	},
	})
}

func (b *BotMessage) Request(url string) (err error) {
	b.MsgType = "post"
	reqBodyStr, err := json.Marshal(b)
	res, err := httpUtil.HttpPost(url, string(reqBodyStr))
	if err != nil {
		service.Log.Error(res)
		return err
	}
	return
}

func (b *BotInteractive) Request(url string) (err error) {
	b.MsgType = "post"
	reqBodyStr, err := json.Marshal(b)
	res, err := httpUtil.HttpPost(url, string(reqBodyStr))
	if err != nil {
		service.Log.Error(res)
		return err
	}
	return
}

func SendStr(str string) {
	var b BotMessage
	var feiContents [][]BotContent
	b.MsgType = "post"
	feiContents = append(feiContents, []BotContent{
		{
			Tag:  "text",
			Text: str,
		},
	})
	b.Content.Post.ZhCn.Content = feiContents
	err := b.Request(service.Conf.Feishu.Bot.TestBot)
	if err != nil {
		return
	}
}
